package com.library.daoImpl;

import com.library.dao.Library_BorrowDao;
import com.library.util.MysqlConnectUtil;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

public class Library_BorrowDaoImpl implements Library_BorrowDao {

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //在借阅之前，获取图书的库存
    private int getCountByISBN(String ISBN) {

        int bookCount = 0;

        try {

            conn = MysqlConnectUtil.getConn();
            //查询库存的sql语句
            String sql_selectCount = "select count from book where ISBN=?";
            ps = conn.prepareStatement(sql_selectCount);

            ps.setString(1,ISBN);

            rs = ps.executeQuery();

            if(rs.next()){
                bookCount = rs.getInt("count");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            MysqlConnectUtil.closed(conn,ps,rs);
        }

        return bookCount;

    }

    /**
     * 通过用户名和ISBN获取借阅ID
     * @param userId
     * @param ISBN
     * @return
     */
    private String getBorrowIdByUserIdAndISBN(String userId,String ISBN){

        String borrowId = "";
        try {
            conn = MysqlConnectUtil.getConn();

            ps = conn.prepareStatement("select borrowId from borrow where userId=? and ISBN=? and backDate is null");

            ps.setString(1,userId);
            ps.setString(2,ISBN);

            rs = ps.executeQuery();

            if(rs.next()){
                borrowId = rs.getString("borrowId");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            MysqlConnectUtil.closed(conn,ps,rs);
        }
        return borrowId;
    }


    /**
     * 通过借阅ID查找应归还日期
     * @param borrowId
     * @return
     */
    private LocalDate getShouldBackDate(String borrowId){

        LocalDate backDate = null;

        try {
            conn = MysqlConnectUtil.getConn();

            ps = conn.prepareStatement("select shouldBackDate from borrow where borrowId=?");

            ps.setString(1,borrowId);

            rs = ps.executeQuery();

            if(rs.next()){
                String backDateStr = rs.getString("shouldBackDate");
                backDate = LocalDate.parse(backDateStr,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            MysqlConnectUtil.closed(conn,ps,rs);
        }

        return backDate;

    }

    @Override
    public boolean borrowBook(String userId, String ISBN) {

        boolean isSuccess = false;

        //获取系统当前时间
        LocalDateTime nowDateTime = LocalDateTime.now();
        //把系统当前时间充当借阅时间
        String borrowDataTime = nowDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //比当前系统时间增加了一个月
        LocalDateTime oneMonthDateTime = nowDateTime.plusMonths(1);
        //用当前时间增加一个月充当应归还日期
        String shouldBackDate = oneMonthDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));


        //先获取库存
        int bookCount = getCountByISBN(ISBN);

        //如果库存足够，可以借阅
        if(bookCount>0){
            try {
                conn = MysqlConnectUtil.getConn();

                String sql_insertBorrowInfo = "insert into borrow values(?,?,?,?,?,?,?,?,?)";

                ps = conn.prepareStatement(sql_insertBorrowInfo);

                ps.setString(1, UUID.randomUUID().toString().toUpperCase());
                ps.setString(2,userId);
                ps.setString(3,ISBN);
                ps.setString(4,borrowDataTime);
                ps.setString(5,shouldBackDate);
                ps.setInt(6,0);
                ps.setString(7,null);
                ps.setDouble(8,0);
                ps.setInt(9,0);

                int insertCount = ps.executeUpdate();

                if(insertCount==1){
                    isSuccess = true;
                }

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                MysqlConnectUtil.closed(conn,ps);
            }

        }else{
            System.out.println("库存不足，无法借阅");
        }

        return isSuccess;
    }

    @Override
    public boolean renewBook(String userId, String ISBN) {

        String borrowId = getBorrowIdByUserIdAndISBN(userId, ISBN);
        LocalDate shouldBackDate = getShouldBackDate(borrowId);
        String renewBackDate = shouldBackDate.plusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));


        boolean isRenewSuccess = false;
        try {
            conn = MysqlConnectUtil.getConn();

            String sql_renewBook = "update borrow set shouldBackDate=?,renewCount=renewCount+1 " +
                    "where userId=? and ISBN=? and renewCount<2 and backDate is null";

            ps = conn.prepareStatement(sql_renewBook);

            ps.setString(1,renewBackDate);
            ps.setString(2,userId);
            ps.setString(3,ISBN);

            int updateCount = ps.executeUpdate();

            if(updateCount==1){
                isRenewSuccess = true;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            MysqlConnectUtil.closed(conn,ps);
        }

        return isRenewSuccess;

    }

    @Override
    public boolean backBook(String userId, String ISBN) {
        return true;
    }
}
